﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using CSRedis;
using NetMicro.Cache;

namespace NetMicro.Cache.DelayBus
{
    /// <summary>
    /// 准备处理任务队列
    /// </summary>
    public static class ReadyQueue
    {
        /// <summary>
        /// 准备处理队列
        /// </summary>
        private const string queuePrefix = "delay-ready-queue:";



        /// <summary>
        /// 压入一个待处理的任务
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="job"></param>
        /// <returns></returns>
        public static Task<long> PushToReadyQueueAsync<T>(this IRedisCache redisCache, string topic, T job) where T : EventJob
        {

            return redisCache.RPushAsync($"{queuePrefix}{topic}",value: Newtonsoft.Json.JsonConvert.SerializeObject(job));

        }

        /// <summary>
        /// 压入一个待处理的任务
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="job"></param>
        /// <returns></returns>
        public static void PushToReadyQueue<T>(this CSRedisClientPipe<string> clientPipe, string topic, T job) where T : EventJob
        {

            clientPipe.RPush($"{queuePrefix}{topic}", Newtonsoft.Json.JsonConvert.SerializeObject(job));

        }

        /// <summary>
        /// 弹出一个任务处理
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="timeoutSeconds"></param>
        /// <returns></returns>
        public static async Task<T> GetJobFromReadyQueueAsync<T>(this IRedisCache redisCache, string topic)
        {
            string data = await redisCache.LPopAsync($"{queuePrefix}{topic}");
            if (string.IsNullOrEmpty(data))
            {
                return default(T);
            }
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(data);
        }

    }
}
